package com.sctvcloud.dongqu.ui.activities;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.mob.tools.utils.DeviceHelper;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.dongqu.BuildConfig;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Cache;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.beans.AdPicItem;
import com.sctvcloud.dongqu.beans.FPage;
import com.sctvcloud.dongqu.beans.ImageUr;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.adapter.holder.AdInfoHolder;
import com.sctvcloud.dongqu.ui.dialog.CheckPermission;
import com.sctvcloud.dongqu.ui.dialog.UserAgreementDiaFragment;
import com.sctvcloud.dongqu.ui.fragment.GreatestFragment;
import com.sctvcloud.dongqu.ui.fragment.HomeFragment;
import com.sctvcloud.dongqu.ui.utils.SkipUtil;
import com.sctvcloud.dongqu.ui.utils.UIUtils;
import com.sctvcloud.dongqu.ui.utils.update.DownloadManager;
import com.sctvcloud.dongqu.utils.StatusBarUtil;
import com.sctvcloud.dongqu.utils.UserManager;
import com.sctvcloud.dongqu.utils.VersionUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import pl.droidsonroids.gif.AnimationListener;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * 启动页
 */
public class SplashActivity extends BaseActivity implements DownloadManager.OnDownloadSuccess {

    //start
    @BindView(R.id.splash_img)
    protected ImageView img;
    @BindView(R.id.img_gif)
    protected GifImageView gifImg;
    @BindView(R.id.skip_cv)
    protected TextView skip_cv;

    @BindView(R.id.act_aplash)
    protected View vStart;
    @BindView(R.id.act_aplash_ad)
    protected View vAdStart;
    pl.droidsonroids.gif.GifDrawable gif;

    private static final long BACK_FROM_TIME = 1500;
    private boolean isGifFinish;
    private boolean hasCallToMain;

    private long startShowTime = -1;
    private ArrayList<Object> adImgs;
    private ArrayList<ImageUr> imageList;
    private int time;
    Timer timer;
    TimerTask task;
    int count = 0;


    private CheckPermission checkPermission;
    private Object toMainObjSync = new Object();

    //ad start

    public final static String APP_VERSION_KEY = "APP_VERSION";
    public final static String START_KEY = "START_PAGE_SETTING";
    private final String KEY_AD = "key_ad";
    @BindView(R.id.splash_time)
    protected TextView time_tv;
    @BindView(R.id.splash_images)
    protected ConvenientBanner<Object> splash_images;
    @BindView(R.id.rl_time)
    protected View vTime;
    private ArrayList<Object> pics;
    private int adTime;

    private CountDownTimer myCountDownTimer;

    private Handler handler;

    private Gson gson;

    private int adCount;

    private CuntDownTask cuntDownRunable;
    private boolean isJump = false;


    private boolean hasCallFinish;
    //首次启动的引导页
    private static Integer[] imgsRes = {R.drawable.app_guide_img_1, R.drawable.app_guide_img_2, R.drawable.app_guide_img_3, R.drawable.app_guide_img_4};
    boolean isFirstStart = false;
    boolean isFromBackground = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setThisImmersive(true);
        super.onCreate(savedInstanceState);
        //设置状态栏透明
//        StatusBarUtil.setTranslucentStatus(this);
        GridsumWebDissector.getInstance().enableActivityTracking(getApplication());
        GridsumWebDissector.getInstance().enableDebug(false);
        isFirstStart = (boolean) SharedPreferencesUtil.getParam(this, START_KEY, true);
        int versionCode = VersionUtil.getVersionCode(this);
        int oldVersion = (int) SharedPreferencesUtil.getParam(this, SplashActivity.APP_VERSION_KEY, 0);
        if (versionCode > oldVersion) {
            isFirstStart = true;//如果升级到了新版本，那么也当做首次启动，展示引导页
            SharedPreferencesUtil.setParam(this, HomeFragment.COLUMN_LIST, "");//升级版本清除栏目存储
            showAgreement();
        } else {
            loadView();
        }
    }

    private void loadView() {
        isFromBackground = getIntent().getBooleanExtra("FROM_TAG", false);
        int isRunning = UIUtils.isBackground(this);
        if (isRunning != 1 || isFromBackground) {//isRunning为2时是启动APP创建启动页的
            handler = new Handler();
            if (!isFromBackground) {
                SharedPreferencesUtil.setParam(this, GreatestFragment.FLOAT_AD_SHOW, true);
                String brand = android.os.Build.BRAND;
                String model = android.os.Build.MODEL;
                String sysVersion = android.os.Build.VERSION.RELEASE;
                SkipUtil.skipToAddUserOperate(this, getOwnerName(), 24, 0
                        , brand + "/" + model + "/" + sysVersion, "", "");

                initUser();
            }
            initStart();
            initPermission();
        } else {
            finish();
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
//        if (myCountDownTimer != null) {
//            myCountDownTimer.cancel();
//        }
        if (checkPermission != null) {
            checkPermission.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        if (myCountDownTimer != null) {
//            myCountDownTimer.cancel();
//        }
    }

    private void initAdStart() {
        findViewById(R.id.splash_skip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickSkip(v);
            }
        });
        pics = new ArrayList<>();
        splash_images.setIs169(false);
        if (!isFirstStart) {
            pics = adImgs;
            vTime.setVisibility(View.VISIBLE);
        } else {
            splash_images.stopTurning();
            for (int i = 0; i < imgsRes.length; i++) {
                pics.add(imgsRes[i]);
            }
            vTime.setVisibility(View.GONE);
        }
        if (ListUtils.isListValued(pics)) {
            vStart.setVisibility(View.GONE);
            vAdStart.setVisibility(View.VISIBLE);
        } else {
            vAdStart.setVisibility(View.GONE);
        }
        splash_images.setCanLoop(false);

        splash_images.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (position == imgsRes.length - 1) {
                    isJump = true;
                } else {
                    isJump = false;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        setAdPic(pics);

    }

    private void initStart() {
        vStart.setVisibility(View.VISIBLE);
        vAdStart.setVisibility(View.GONE);
        task = new TimerTask() {
            @Override
            public void run() {
                count--;
                if (count <= 0) {
//                    toAd(true);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            initAdStart();
                        }
                    });

                }
            }
        };
//        try {
//            Bitmap bm=new GifDrawable(getResources(), R.drawable.splash).seekToFrameAndGet(0);
//            if (bm!=null){
//                img.setImageBitmap(bm);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        if (!isFromBackground) {
            checkPermission = new CheckPermission(this);
            checkPermission.updateVersion2(this);//检测版本升级
        } else {
            getAdPic();
        }

    }

    private void loadGif() {
        if (isFirstStart) {
//            toAd(false);
            initAdStart();
            return;
        }
        skip_cv.setVisibility(View.VISIBLE);
        setFlickerAnimation(skip_cv);
        skip_cv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                skip_cv.clearAnimation();
//                toAd(true);
                toMain(true);
            }
        });

        try {
            String gifFilePath = (String) SharedPreferencesUtil.getParam(this, "GIF_PATH", "");
            if (!TextUtils.isEmpty(gifFilePath)) {
                File file = new File(gifFilePath);
                if (file.exists()) {
                    if (gifFilePath.endsWith(".gif")) {
                        gifImg.setVisibility(View.VISIBLE);
                        img.setVisibility(View.GONE);
                        gif = new pl.droidsonroids.gif.GifDrawable(file);
                    } else {
                        gifImg.setVisibility(View.GONE);
                        img.setVisibility(View.VISIBLE);
                        count = (int) SharedPreferencesUtil.getParam(this, "TIME", 0);
                        Bitmap bitmap = BitmapFactory.decodeFile(gifFilePath);
                        img.setImageBitmap(bitmap);
                        timer = new Timer();
                        timer.schedule(task, 1000, 1000);
                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (gifImg != null && gif != null) {
            gifImg.setVisibility(View.VISIBLE);
            gifImg.setImageDrawable(gif);
            gif.addAnimationListener(new AnimationListener() {
                @Override
                public void onAnimationCompleted(int loopNumber) {
                    JLog.e("loopNumber :" + loopNumber);
                    gif.stop();
                    toMain(true);
                }
            });

        } else {
            gifImg.setVisibility(View.GONE);
            startCuntDown(1, 3);
        }
    }

    /**
     * 请求获取广告图片
     */
    private void getAdPic() {
        String url = "sctv/startPage.json";
        NetUtils.getNetAdapter().getAdList(getOwnerName(), url, new AbsNetCallBack<AdPicItem>(AdPicItem.class) {
            @Override
            public void onSuc(AdPicItem adPicItem) {

                if (adPicItem != null && ListUtils.isListValued(adPicItem.getChannel())) {
                    AdPicItem.ImageListItem listItem = adPicItem.getChannel().get(0);
                    if (ListUtils.isListValued(listItem.getImageList())) {
                        imageList = listItem.getImageList();
                        adImgs = new ArrayList<>();
                        for (ImageUr imageUr : listItem.getImageList()) {
                            adImgs.add(imageUr.getImageUrl());
                        }
                        time = listItem.getShowTime();
                        initAdStart();

                    } else {
                        //如果没有广告图片，就使用GIF图片
                        loadGif();
                    }
                } else {
                    loadGif();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                loadGif();
            }
        });

    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
    }

    private synchronized void toAd(boolean isGifFinished) {
        if (timer != null) {
            timer.cancel();
        }
        if (task != null) {
            task.cancel();
        }
//        if (isGifFinished) {
//            this.isGifFinish = true;
//        } else {
//            return;
//        }
//        if (adImgs == null || adImgs.size() == 0) {
////            toMain(true);
//            loadGif();
//            return;
//        }

        Intent intent = new Intent(this, SplashAdActivity.class);
        if (getIntent().hasExtra(EX_TYPE)) {
            Intent in = getIntent();
            intent.putExtra(EX_TYPE, in.getIntExtra(EX_TYPE, -1));
            intent.putExtra(EX_DATA, in.getSerializableExtra(EX_DATA));
        } else {
            intent.putExtra("AD_IMGS", adImgs);
            intent.putExtra("AD_TIME", time);
        }
        startActivity(intent);
        finish();
        overridePendingTransition(0, 0);
    }

    private synchronized void toMain(boolean isGifFinished) {
        if (isFromBackground) {
            finish();
            overridePendingTransition(0, 0);
            return;
        }
        if (isGifFinished) {
            this.isGifFinish = true;
        } else {
            return;
        }

        Intent intent = new Intent(this, MyMainActivity.class);
        if (getIntent().hasExtra(EX_TYPE)) {
            JLog.e("hase ex Skip");
            Intent in = getIntent();
            intent.putExtra(EX_TYPE, in.getIntExtra(EX_TYPE, -1));
            intent.putExtra(EX_DATA, in.getSerializableExtra(EX_DATA));
        }
        startActivity(intent);
        finish();
        overridePendingTransition(0, 0);
    }

    private void getGifUrl() {
        String url = "http://scgcfile.sctv.com:2225/scfouces/scgc2/StartPage/list.json";
        x.http().get(new RequestParams(url), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject obj = new JSONObject(result);
                    String rs = obj.getString("rs");
                    if (rs.equals("ok")) {
                        JSONObject data = obj.getJSONObject("data");
                        JSONArray newsList = data.getJSONArray("newsList");
                        ArrayList<FPage> pageBeens = new ArrayList<FPage>();
                        for (int j = 0; j < newsList.length(); j++) {
                            JSONObject jsonObject = newsList.getJSONObject(j);
                            FPage fPage = new FPage();
                            fPage.setNewsUrl(jsonObject.optString("newsUrl"));
                            fPage.setNewsImageName(jsonObject.optString("newsImageName"));
                            fPage.setNewsImage(jsonObject.optString("newsImage"));
                            fPage.setShowTimeLength(jsonObject.optString("showTimeLength"));
                            fPage.setNewsType(jsonObject.optString("newsType"));
                            pageBeens.add(fPage);

                        }
                        // pageBeens.remove(pageBeens.size() - 1);
                        String gifUrl = "";
                        int time = 0;
                        for (FPage fPage : pageBeens) {
                            if ("11".equals(fPage.getNewsType())) {
                                String fileUrlStr = fPage.getNewsImage();
                                String[] fileUrls = fileUrlStr.split(";");
                                gifUrl = fileUrls[0];
                                time = Integer.parseInt(fPage.getShowTimeLength());
                            } else if ("10".equals(fPage.getNewsType()) && !TextUtils.isEmpty(fPage.getNewsImage())) {
                                setPages(fPage.getNewsImage(), fPage.getShowTimeLength());
                            }
                        }
                        loadGif(gifUrl, time);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                cex.printStackTrace();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void setFlickerAnimation(View iv_chat_head) {
        final Animation animation = new AlphaAnimation(1, 0); // Change alpha
        animation.setDuration(1000); // duration - half a second
        animation.setInterpolator(new LinearInterpolator()); // do not alter
        animation.setRepeatCount(Animation.INFINITE); // Repeat animation
        animation.setRepeatMode(Animation.REVERSE); //
        iv_chat_head.setAnimation(animation);
    }

    private void loadGif(String fileUrl, final int time) {
        String localFileUrl = (String) SharedPreferencesUtil.getParam(this, "GIF_URL", "");
        String localFileName = (String) SharedPreferencesUtil.getParam(this, "GIF_NAME", "");
        String fileName = "";
        if (!TextUtils.isEmpty(fileUrl)) {
            fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        }

        if ((TextUtils.isEmpty(localFileUrl) || TextUtils.isEmpty(fileUrl)) || !localFileUrl.equals(fileUrl)) {
            DownloadManager loadManager = new DownloadManager(this, fileName, fileUrl);
            loadManager.downloadFile(new DownloadManager.DownloadListener() {
                @Override
                public void onDownloadFinish(String fileUrl, String fileName, String path) {
                    SharedPreferencesUtil.setParam(SplashActivity.this, "GIF_URL", fileUrl);
                    SharedPreferencesUtil.setParam(SplashActivity.this, "GIF_NAME", fileName);
                    SharedPreferencesUtil.setParam(SplashActivity.this, "GIF_PATH", path + fileName);
                    SharedPreferencesUtil.setParam(SplashActivity.this, "TIME", time);
                    String pathTemp = (String) SharedPreferencesUtil.getParam(SplashActivity.this, "GIF_PATH", "");
                    Log.e("onDownloadFinish:", "onDownloadFinish: " + pathTemp);
                }
            });
        }
    }

    private String mSavePath;
    private String fileName;

    @Override
    public void onDownloadSuccess(String mSavePath, String fileName) {
        //下载安装包成功回调
        this.mSavePath = mSavePath;
        this.fileName = fileName;
        reqestPermission();
    }


    /**
     * 判断未知来源包安装权限
     */
    private void reqestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean hasInstallPermission = getPackageManager().canRequestPackageInstalls();
            if (!hasInstallPermission) {
                startInstallPermissionSettingActivity(this);
            } else {
                installApk(mSavePath, fileName);//高于8.0的，但有未知来源安装权限直接安装
            }
        } else {
            installApk(mSavePath, fileName);//低于8.0的直接安装
        }
    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity(Context context) {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, 1000);
    }

    /**
     * 安装APK文件
     */
    private void installApk(String mSavePath, String fileName) {
        if (!TextUtils.isEmpty(mSavePath) && !TextUtils.isEmpty(fileName)) {
            File apkfile = new File(mSavePath, fileName);
            if (!apkfile.exists()) {
                return;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri u = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                u = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", apkfile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                u = Uri.fromFile(apkfile);
            }
            intent.setDataAndType(u, "application/vnd.android.package-archive");
            startActivity(intent);
        } else {
            Toast.makeText(this, "安装文件为空", Toast.LENGTH_LONG).show();
        }
    }

    private void setPages(String imageUrls, String time) {
        if (TextUtils.isEmpty(time)) {
            this.time = 3;
        } else {
            this.time = Integer.parseInt(time);
        }

        if (!TextUtils.isEmpty(imageUrls)) {
            adImgs = new ArrayList<>();
            String[] imgs = imageUrls.split(";");
            for (String str : imgs) {
                adImgs.add(str);
            }
        }
    }

//    private boolean toMainCheck() {
//        if (checkPermission == null || checkPermission.hasCheckFinish()) {
//            toMain(true);
//            return true;
//        } else {
//            hasCallToMain = true;
//            return false;
//        }
//    }

//    private boolean toMainSync() {
//        synchronized (toMainObjSync) {
//            return toMainCheck();
//        }
//    }

    @Override
    public int onOtherCallback(Message msg) {
        if (msg != null) {
            if (msg.what == CheckPermission.WHAT_FINISH) {
                skip_cv.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (toMainObjSync) {
//                            if (hasCallToMain) {
//                                toMain(true);
//                            }
                            getAdPic();
                        }
                    }
                }, 200);
            }
        }
        return super.onOtherCallback(msg);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (checkPermission != null) {
            checkPermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == checkPermission.SETTING_REQUEST) {
            if (checkPermission != null) {
                checkPermission.onActivityResult();
            }
        } else if (resultCode == RESULT_OK && requestCode == 1000) {
            installApk(mSavePath, fileName);//再次执行安装流程，包含权限判等
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (checkPermission != null) {
            checkPermission.onSaveInstance();
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (checkPermission != null) {
            checkPermission.onRestoreInstance();
        }
    }


    /**
     * 判断当前APP版本是否与之前一致；
     * 如果已升级，那么去除用户登录状态，并且更新版本记录
     */
    private void initUser() {
        UserManager.init(this);
        int version = DeviceHelper.getInstance(this).getAppVersion();
        int temp = SharedPreferencesUtil.getSharedPreferenceInstance(this).getInt("versionTemp", 0);
        if (version > temp) {
            if (UserManager.isLoginS()) {
                UserManager.getInstance().setUser(this, null);
                UserManager.getInstance().delUserCache(this);
            }
            SharedPreferencesUtil.setParams(this, "versionTemp", version);
        }
    }

    boolean hasExit = false;

    private void toMain() {
        if (isFromBackground) {
            finish();
            overridePendingTransition(0, 0);
            return;
        }
        if (hasExit) {
            return;
        }
        myCountDownTimer = null;
        Intent intent = new Intent(this, MyMainActivity.class);
        startActivity(intent);
        hasExit = true;
        finish();
        overridePendingTransition(0, 0);
    }


    /**
     * 设置轮播图片
     *
     * @param woAdavertising
     */
    private void setAdPic(List<Object> woAdavertising) {
        if (woAdavertising != null) {
            try {
                setBannerPic(woAdavertising);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 倒计时切换
     *
     * @param pos
     * @param length
     */
    private synchronized void startCuntDown(int pos, int length) {

//        if (isFromBackground) {
////            myCountDownTimer = new MyCountDownTimer(BACK_FROM_TIME, 100);
////            myCountDownTimer.start();
//            if(null!=myCountDownTimer){
//                myCountDownTimer.cancel();
//                myCountDownTimer = null;
//            }
//            myCountDownTimer = new CountDownTimer(BACK_FROM_TIME, 500) {
//
//                public void onTick(long millisUntilFinished) {
//                    JLog.e("-----millisUntilFinished--" + millisUntilFinished);
//                }
//
//                public void onFinish() {
//                    JLog.e("-----millisUntilFinished--onFinish  hasCallFinish="+hasCallFinish );
////                    onCountDownFinish();
//                    finish();
//                    hasCallFinish = true;
//                    overridePendingTransition(0, 0);
//                }
//            };
//            myCountDownTimer.start();
//
//        } else {
        if (cuntDownRunable != null) {
            handler.removeCallbacks(cuntDownRunable);
        }
        if (!isFirstStart) {
            if (isFromBackground) {
                cuntDownRunable = new CuntDownTask(1, 2, 750);
            } else {
                cuntDownRunable = new CuntDownTask(pos, length);
            }
        }
        handler.post(cuntDownRunable);
//        }
    }

    private synchronized void onCountDownFinish() {
        if (hasCallFinish) {
            return;
        }
        toMain();
        finish();
        hasCallFinish = true;
        overridePendingTransition(0, 0);
    }


    //设置轮播资源
    private void setBannerPic(final List<Object> wad) {


        if (wad != null && wad.size() > 0) {
            splash_images.setPages(new CBViewHolderCreator() {
                @Override
                public Object createHolder() {
                    return new AdInfoHolder();
                }
            }, wad)
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
//设置点击事件
            splash_images.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    if ((imgsRes.length == 1 || isJump) && isFirstStart) {
                        toMain();
                    } else if (!isFirstStart && null != imageList && imageList.size() > 0) {
                        Intent intent1 = new Intent(SplashActivity.this, MyMainActivity.class);
                        Intent intent = null;
                        ImageUr img = imageList.get(position);
                        if (null != img && null != img.getNewsUrlList() && img.getNewsUrlList().size() > 0) {
                            String newsUrl = img.getNewsUrlList().get(0).getNewsUrl();
                            if (!TextUtils.isEmpty(newsUrl)) {
                                Cache.getInstance().setStartAdClicked(true);
                                intent = new Intent(SplashActivity.this, NewesDetailActivity.class);
                                intent.putExtra(BaseActivity.EX_URL, newsUrl);
                            }
                        }
                        if (null != intent) {
                            Intent[] intents = new Intent[2];
                            intents[0] = intent1;
                            intents[1] = intent;
                            startActivities(intents);
                        } else {
                            startActivity(intent1);
                        }
                        hasExit = true;
                        finish();
                    }
                }
            });
            splash_images.hideBottom(true);

//设置自动跳转时间
            adCount = wad.size();
            if (!splash_images.isTurning() && !isFirstStart) {
                startCuntDown(adCount, time);
                splash_images.startTurning(time * 1000);
            }
        }
    }

    //    @Event(value = {R.id.splash_skip})
    private void onClickSkip(View view) {
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
            myCountDownTimer = null;
        }
        onCountDownFinish();
    }

    /**
     * 获取动态权限
     */
    private void initPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            //超过Android大于5.1 （即6.0以上）版本需要申请权限
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_SETTINGS};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
    }


//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        // If request is cancelled, the result arrays are empty.
//        if (grantResults.length > 0) {
//            // permission was granted, yay! Do the
//            // contacts-related task you need to do.
//            //权限申请成功，初始化异常日志的打印，以及跳转到主页
//            int result = 0;
//            for (int i = 0; i < grantResults.length; i++) {
//                result += grantResults[i];
//            }
//            if (result != 0) {
//                Toast.makeText(this, "部分权限申请失败，无法正常使用，请重试", Toast.LENGTH_LONG).show();
//            }
//        } else {
//            // permission denied, boo! Disable the
//            // functionality that depends on this permission.
//            Toast.makeText(this, "权限申请失败，无法正常使用，请重试", Toast.LENGTH_LONG).show();
//        }
//    }

    private class CuntDownTask implements Runnable {
        private int adPos;
        private int showTime;
        private int count;
        private int dil;

        public CuntDownTask(int showTime) {
            this.showTime = showTime;
        }

        public CuntDownTask(int adPos, int showTime) {
            Log.e("CuntDownTask", "adPos:" + adPos + " showTime:" + showTime);
            this.adPos = adPos;
            this.showTime = showTime;
            count = showTime;
            dil = 1000;
        }

        public CuntDownTask(int adPos, int showTime, int dil) {
            Log.e("CuntDownTask", "adPos:" + adPos + " showTime:" + showTime);
            this.adPos = adPos;
            this.showTime = showTime;
            count = showTime;
            this.dil = dil;
        }

        public void setCountDownInfo(int adPos, int showTime) {
            this.adPos = adPos;
            this.showTime = showTime;
            count = showTime;
        }

        @Override
        public void run() {
            time_tv.setText(count + "");
            count--;
            if (count >= 0) {
                handler.postDelayed(this, dil);
            } else {
                adPos--;
                if (adPos <= 0) {
                    Log.e("CuntDownTask", "onCountDownFinish");
                    onCountDownFinish();
                } else {
                    count = showTime;
                    handler.postDelayed(this, dil);
                }

            }
        }
    }

//    /**
//     * 设置倒计时
//     */
//    class MyCountDownTimer extends CountDownTimer {
//
//
//        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
//            super(millisInFuture, countDownInterval);
//        }
//
//        @Override
//        public void onTick(long millisUntilFinished) {
////            int time = (int) millisUntilFinished / 1000;
////            time_tv.setText(time + "");
//            JLog.e("-----millisUntilFinished--" + millisUntilFinished);
//        }
//
//        @Override
//        public void onFinish() {
//            JLog.e("-----millisUntilFinished-onFinish-");
////            time_tv.setText(0 + "");
//            onCountDownFinish();
//           /* toMain();
//            finish();*/
//
//        }
//    }


    @Override
    protected void onDestroy() {
        if (null != myCountDownTimer) {
            myCountDownTimer.cancel();
        }
        if (splash_images != null && splash_images.isTurning()) {
            splash_images.stopTurning();
        }
        if (cuntDownRunable != null) {
            handler.removeCallbacks(cuntDownRunable);
            cuntDownRunable = null;
        }
        super.onDestroy();
    }

    private UserAgreementDiaFragment readDiaFragment;

    /**
     * 首次启动 提示用户查看用户协议
     */
    private void showAgreement() {
        readDiaFragment = new UserAgreementDiaFragment();
        if (!readDiaFragment.isShow()) {
            readDiaFragment.setCallBack(callBack);
            readDiaFragment.show(this.getSupportFragmentManager(), "");
        }
    }

    //Dialog点击回调
    public BaseDialogFragment.ICallBack callBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == UserAgreementDiaFragment.CANCEL) {
                //TODO　退出
                finish();
                exit();
            } else if (msg.what == UserAgreementDiaFragment.CONFIRM) {
                //TODO 已阅
                loadView();
            } else if (msg.what == UserAgreementDiaFragment.AGREEMENT) {
                //TODO 加载用户协议
                Intent intent = new Intent(SplashActivity.this, UserAgreementActivity.class);
                intent.putExtra(UserAgreementActivity.RULE_TYPE, 0);
                startActivity(intent);
            } else if (msg.what == UserAgreementDiaFragment.POLICY) {
                //TODO 加载隐私政策
                Intent intent = new Intent(SplashActivity.this, UserAgreementActivity.class);
                intent.putExtra(UserAgreementActivity.RULE_TYPE, 1);
                startActivity(intent);
            }
        }
    };

    /**
     * 退出APP
     */
    public void exit() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        manager.restartPackage(getPackageName());
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);

    }
}
